package com.szsky.sky.producer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.szsky.sky.dto.mq.ToZeroProducerDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.*;

@Slf4j
@Component
public class UumToZeroProducer {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Value("${mq.topic}")
    private String topic;

    @Value("${mq.tag}")
    private String tag;

    /**
     * 同步发送消息（适合核心业务，有返回结果）
     */
    public void sendSyncMessage(ToZeroProducerDto payload) {
        // 消息目的地格式：topic:tag（tag用于消息过滤，可选）
        String destination = topic + ":" + tag;

        // 2. 生成唯一消息key
        String messageKey = generateMessageKey();

        // 构造消息并设置 keys

        Map<String,Object> map = new HashMap<>();
        map.put("msgId",messageKey);
        map.put("msgType","user");
        map.put("timestamp", String.valueOf(Instant.now().toEpochMilli()));
        List<ToZeroProducerDto> data = new ArrayList<>();
        data.add(payload);
        map.put("data", data);

        Message<String> message = MessageBuilder.withPayload(JSONObject.toJSONString(map))
                .setHeader(RocketMQHeaders.KEYS, messageKey)
                .setHeader("content-type", "application/json").build();


        rocketMQTemplate.send(destination, message);
    }

    /**
     * 生成唯一消息key
     */
    private String generateMessageKey() {
        // 格式：业务前缀 + 时间戳 + 随机串
        return "MSG_" + System.currentTimeMillis() + "_" +
                UUID.randomUUID().toString().replace("-", "").substring(0, 12);
    }

    /**
     * 将消息内容转换为字节数组
     */
    private byte[] convertPayloadToBytes(Object payload) {
        if (payload instanceof String) {
            // 如果是字符串，直接按UTF-8编码
            return ((String) payload).getBytes(StandardCharsets.UTF_8);
        } else {
            // 如果是对象，序列化为JSON（需要引入JSON工具，如FastJSON）
            return com.alibaba.fastjson.JSON.toJSONString(payload).getBytes(StandardCharsets.UTF_8);
        }
    }
}
